package com.leon.classify.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;

import com.leon.classify.domain.AdvertPic;
import com.leon.classify.domain.Area;
import com.leon.classify.domain.Comment;
import com.leon.classify.domain.CommentDetail;
import com.leon.classify.domain.Company;
import com.leon.classify.domain.FirstClass;
import com.leon.classify.domain.HeadAdvert;
import com.leon.classify.domain.HeadAdvertList;
import com.leon.classify.domain.LeftRecommon;
import com.leon.classify.domain.MiddleArea;
import com.leon.classify.domain.RightArea;
import com.leon.classify.domain.SecondClass;
import com.leon.classify.service.ClassifyService;
import com.leon.common.action.BaseAction;
import com.leon.common.util.VVMappingUtil;
import com.leon.module.service.ModuleService;
import com.leon.picture.service.PictureService;

public class ClassifyAction extends BaseAction {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 3764011872804639367L;
	private static final int BUFFER_SIZE = 16 * 1024 ;
	private ClassifyService classifyService;
	private ModuleService moduleService;
	private PictureService pictureService;
	private final static String SUCCESSMSG="{success:true}";
	
	private List<FirstClass> fcList;//一级分类集合
	private List<Area> areaList; //所有模块集合
	private List<HeadAdvert> haList;
	private List <HeadAdvert>lhaList;//头部左边广告集合
	private List <HeadAdvert>rhaList;//头部右边广告集合
	private List<AdvertPic> aplist;//二级页面图片
	private List<AdvertPic> headAps;
	private Company company;
	private SecondClass seconds;
	private FirstClass fc;
	private List<Area> scAreaList=new ArrayList<Area>();
	private HeadAdvertList hal;
	private HeadAdvert headAdvert;
	
	public HeadAdvertList getHal() {
		return hal;
	}
	public void setHal(HeadAdvertList hal) {
		this.hal = hal;
	}
	public Company getCompany() {
		return company;
	}
	public void setCompany(Company company) {
		this.company = company;
	}
	public List<Area> getAreaList() {
		return areaList;
	}
	public void setAreaList(List<Area> areaList) {
		this.areaList = areaList;
	}
	public List<FirstClass> getFcList() {
		return fcList;
	}
	public void setFcList(List<FirstClass> fcList) {
		this.fcList = fcList;
	}
	public ClassifyService getClassifyService() {
		return classifyService;
	}
	public void setClassifyService(ClassifyService classifyService) {
		this.classifyService = classifyService;
	}
	public ModuleService getModuleService() {
		return moduleService;
	}
	public void setModuleService(ModuleService moduleService) {
		this.moduleService = moduleService;
	}
	/**
	 * 得到所有的一级分类
	 * @return
	 * @throws IOException 
	 */
	public void getFirstClassify() throws IOException{
		List <FirstClass>list=null;
		list=classifyService.getFirstClassify();
		StringBuffer str=new StringBuffer("[");
		if(list!=null && list.size()>0){
			for(FirstClass fc:list){
				str.append("{text:'"+fc.getClassName()+"',id:'"+fc.getFirstClassId()+"',type:'first'");
				Set<SecondClass> sec=fc.getSecondClasses();
				if(sec!=null && sec.size()>0){
					str.append(",children:[");
					for(SecondClass sc:sec){
						str.append("{text:'"+sc.getClassName()+"',id:'"+sc.getSecClassId()+"',type:'second'");
						Set<Company> coms=sc.getCompanies();
						if(coms!=null && coms.size()>0){
							str.append(",children:[");
							for(Company c:coms){
								str.append("{text:'"+c.getCompanyName()+"',id:'"+c.getCompanyId()+"',type:'company',leaf:true},");
							}
							str.deleteCharAt(str.length()-1);
							str.append("]");
						}else{
							str.append(",leaf:true");
						}
						str.append("},");
					}
					str.deleteCharAt(str.length()-1);
					str.append("]");
				}else{
					str.append(",leaf:true");
				}
				str.append("},");
			}
			str.deleteCharAt(str.length()-1);
			str.append("]");
			this.sendMessage(str.toString());
		}
	}
	/**
	 * 添加一个分类
	 * @throws IOException
	 */
	public void createFirstClassify() throws IOException{
		String className=this.getRequest().getParameter("className");
		String classDesc=this.getRequest().getParameter("classDesc");
		String displayOrder=this.getRequest().getParameter("displayOrder");
		String firstClassId=this.getRequest().getParameter("classId");//为空创建一级分类，如果为id则创建二级分类
		if(classDesc.equals("")){
			classDesc="";
		}
		if(displayOrder.equals("")){
			displayOrder="1";
		}
		if(firstClassId.equals("")){
			FirstClass fc=new FirstClass();
			fc.setClassName(className);
			fc.setClassDesc(classDesc);
			fc.setDisplayOrder(Integer.valueOf(displayOrder));
			fc.setState(1);
			classifyService.createClassify(fc);
		}else{
			SecondClass sc=new SecondClass();
			sc.setClassName(className);
			sc.setClassDesc(classDesc);
			sc.setDisplayOrder(Integer.valueOf(displayOrder));
			sc.setFirstClass(classifyService.getFirstClass(firstClassId));
			sc.setState(1);
			classifyService.createClassify(sc);
		}
		this.sendMessage(SUCCESSMSG);
	}
	/**
	 * 删除分类
	 */
	public void deleteFirstClassify(){
		String classId=this.getRequest().getParameter("classId");
		String type=this.getRequest().getParameter("type");
		if(type.equals("first")){
			classifyService.deleteFirstClassify(classId);
		}else if(type.equals("second")){
			classifyService.deleteSecondClassify(classId);
		}else if(type.equals("company")){
			classifyService.deleteCompany(classId);
		}
		
	}
	/**
	 * 得到一个Classify
	 */
	public void loadFirstClassify(){
		String classId=this.getRequest().getParameter("classId");
		FirstClass fc=classifyService.getFirstClass(classId);
		String str=VVMappingUtil.object2json(fc);
		this.sendMessage("{success: true,data:["+str+"]}");
	}
	/**
	 * 修改一个firstCLass
	 */
	public void updateFirstClassify(){
		String classId=this.getRequest().getParameter("classId");
		FirstClass fc=classifyService.getFirstClass(classId);
		
		String className=this.getRequest().getParameter("className");
		String classDesc=this.getRequest().getParameter("classDesc");
		String displayOrder=this.getRequest().getParameter("displayOrder");
		int state=Integer.valueOf(this.getRequest().getParameter("state"));
		if(classDesc.equals("")){
			classDesc="";
		}
		if(displayOrder.equals("")){
			displayOrder="1";
		}
		fc.setClassDesc(classDesc);
		fc.setClassName(className);
		fc.setState(state);
		fc.setDisplayOrder(Integer.valueOf(displayOrder));
		classifyService.updateFirstClassify(fc);
		this.sendMessage(SUCCESSMSG);
		
	}
	/**
	 * 得到一个二级分类
	 */
	public void loadSecondClassify(){
		String classId=this.getRequest().getParameter("classId");
		SecondClass sc=classifyService.getSecondClass(classId);
		String str=VVMappingUtil.object2json(sc);
		this.sendMessage("{success: true,data:["+str+"]}");
	}
	/**
	 * 修改二级分类时用到的所有一级分类
	 */
	
	public void loadAllFirstClassify(){
		String classId=this.getRequest().getParameter("classId");
		SecondClass sc=classifyService.getSecondClass(classId);
		List<FirstClass>list=classifyService.getFirstClassify();
		StringBuffer str=new StringBuffer("{value:'"+sc.getFirstClass().getFirstClassId()+"',data:");
		str.append(this.FirstClass2Store(list,""));
		str.append("}");
		this.sendMessage(str.toString());
	}
	/**
	 * 模块修改时用到的所有一级分类
	 */
	public void loadAllFCByArea(){
		String leftRecId=this.getRequest().getParameter("leftRecommonId");
		List<FirstClass>list=classifyService.getFirstClassify();
		StringBuffer str=new StringBuffer("{available:");
		str.append(this.FirstClass2Store(list,leftRecId));
		str.append("}");
		this.sendMessage(str.toString());
	}
	/**
	 * 将一级分类转换为Store
	 * @param list
	 * @return
	 */
	public String FirstClass2Store(List<FirstClass>list,String leftRecId){
		StringBuffer str=new StringBuffer("[");
		StringBuffer selected=new StringBuffer(",selected:[");
		if(list.size()>0&& list!=null){
			for(FirstClass fc:list){
				//判断是否是从分类修改来取得，如果是从分类取得 则全部返回，如果是从模块来取的则把已选的跳过
				if(fc.getLeftRecommon()!=null && !leftRecId.equals("")){
					if(fc.getLeftRecommon().getLeftRecommonId().equals(leftRecId)){
						selected.append("['"+fc.getFirstClassId()+"','"+fc.getClassName()+"'],");
						continue;
					}
				}
				str.append("['"+fc.getFirstClassId()+"','"+fc.getClassName()+"'],");
			}
			if(selected.charAt(selected.length()-1)==','){
				selected.deleteCharAt(selected.length()-1);
			}
			if(str.charAt(str.length()-1)==','){
				str.deleteCharAt(str.length()-1);
			}
		}
		selected.append("]");
		str.append("]"+selected);
		return str.toString();
	}
	/**
	 * 修改二级分类
	 * 如果改变了二级分类的父类则改变成对应的一级分类
	 */
	public void updateSecondClassify(){
		String classId=this.getRequest().getParameter("classId");
		SecondClass sc=classifyService.getSecondClass(classId);
		
		String className=this.getRequest().getParameter("className");
		String classDesc=this.getRequest().getParameter("classDesc");
		String displayOrder=this.getRequest().getParameter("displayOrder");
		int state=Integer.valueOf(this.getRequest().getParameter("state"));
		String firstClassId=this.getRequest().getParameter("firstClassId");
		if(classDesc.equals("")){
			classDesc="";
		}
		if(displayOrder.equals("")){
			displayOrder="1";
		}
		if(!sc.getFirstClass().getFirstClassId().equals(firstClassId)){
			FirstClass fc=classifyService.getFirstClass(firstClassId);
			sc.setFirstClass(fc);
		}
		sc.setClassDesc(classDesc);
		sc.setClassName(className);
		sc.setDisplayOrder(Integer.valueOf(displayOrder));
		sc.setState(state);
		classifyService.updateSecondClassify(sc);
		this.sendMessage(SUCCESSMSG);
	}
	/**
	 * 试用response发送数据到HTML
	 * @param str
	 */
	public void sendMessage(String str){
		try {
			this.getResponse().getWriter().write(str);
			this.getResponse().getWriter().flush();
			this.getResponse().getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 创建或更新公司信息
	 */
	public void createCompany(){
		String classId=this.getRequest().getParameter("classId");
		String companyId=this.getRequest().getParameter("companyId");
		Company c;int state;
		SecondClass sc=classifyService.getSecondClass(classId);
		if(companyId==null){
			System.out.println(1);
			c=new Company();
			state=1;
		}else{
			System.out.println(2);
			c=classifyService.getCompany(companyId);
			state=Integer.valueOf(this.getRequest().getParameter("state"));
		}
		
		String companyName=this.getRequest().getParameter("companyName");
		String companyDesc=this.getRequest().getParameter("companyDesc");
		String linkMan=this.getRequest().getParameter("linkMan");
		String phone=this.getRequest().getParameter("phone");
		String address=this.getRequest().getParameter("address");
		String busLine=this.getRequest().getParameter("busLine");
		String siteUrl=this.getRequest().getParameter("siteUrl");
		String briefInfo=this.getRequest().getParameter("briefInfo");
		String displayOrder=this.getRequest().getParameter("displayOrder");
		System.out.println("------------------::"+companyName);
		if(displayOrder.equals("")){
			displayOrder="1";
		}
		c.setSecondClass(sc);
		c.setCompanyName(companyName);
		c.setCompanyDesc(companyDesc);
		c.setLinkMan(linkMan);
		c.setPhone(phone);
		c.setAddress(address);
		c.setBusLine(busLine);
		c.setSiteUrl(siteUrl);
		c.setBriefInfo(briefInfo);
		c.setDisplayOrder(Integer.valueOf(displayOrder));
		c.setState(state);
		
		classifyService.createCompany(c);
		this.sendMessage("{success:true}");
		
	}
	/**
	 * 得到一个company用于修改
	 */
	public void loadCompany(){
		String companyId=this.getRequest().getParameter("companyId");
		Company c =classifyService.getCompany(companyId);
		String str=VVMappingUtil.object2json(c);
		this.sendMessage("{success: true,data:["+str+"]}");
		this.sendMessage(str.toString());
	}
	/**
	 * 得到所有的二级分类用于改变一个company的所属分类
	 */
	public void loadAllSecondClassify(){
		String companyId=this.getRequest().getParameter("companyId");
		Company c =classifyService.getCompany(companyId);
		List<SecondClass>scs=classifyService.getSecondClassify();
		StringBuffer str=new StringBuffer("{value:'"+c.getSecondClass().getSecClassId()+"',data:");
		str.append(this.secondClass2Store(scs,""));
		str.append("}");
		this.sendMessage(str.toString());
	}
	/**
	 * 模块修改时用到的所有二级分类
	 */
	public void loadAllSCByArea(){
		List<SecondClass>scs=classifyService.getSecondClassify();
		String middleAreaId=this.getRequest().getParameter("middleAreaId");
		StringBuffer str=new StringBuffer("{available:");
		str.append(this.secondClass2Store(scs,middleAreaId));
		str.append("}");
		this.sendMessage(str.toString());
	}
	/**
	 * 将二级分类转换为store
	 * @param scs
	 * @return
	 * 
	 */
	public String secondClass2Store(List <SecondClass> scs,String middleAreaId){
		StringBuffer str=new StringBuffer("[");
		StringBuffer selected=new StringBuffer(",selected:[");
		if(scs!=null && scs.size()>0){
			for(SecondClass sc:scs){
				if(sc.getMiddleArea()!=null && !middleAreaId.equals("")){
					if(sc.getMiddleArea().getMiddleAreaId().equals(middleAreaId)){
						selected.append("['"+sc.getSecClassId()+"','"+sc.getClassName()+"'],");
						continue;
					}
				}
				str.append("['"+sc.getSecClassId()+"','"+sc.getClassName()+"'],");
			}
			if(selected.charAt(selected.length()-1)==','){
				selected.deleteCharAt(selected.length()-1);
			}
			if(str.charAt(str.length()-1)==','){
				str.deleteCharAt(str.length()-1);
			}
		}
		selected.append("]");
		str.append("]"+selected);
		return str.toString();
	}
	
	/**
	 * 模块修改时用到的所有二级分类
	 */
	public void loadAllSCByRightArea(){
		List<SecondClass>scs=classifyService.getSecondClassify();
		String rightAreaId=this.getRequest().getParameter("rightAreaId");
		StringBuffer str=new StringBuffer("{available:");
		str.append(this.secondClass2RightStore(scs,rightAreaId));
		str.append("}");
		this.sendMessage(str.toString());
	}
	
	/**
	 * 将二级分类转换为store
	 * @param scs
	 * @return
	 * 
	 */
	public String secondClass2RightStore(List <SecondClass> scs,String rightAreaId){
		StringBuffer str=new StringBuffer("[");
		StringBuffer selected=new StringBuffer(",selected:[");
		if(scs!=null && scs.size()>0){
			for(SecondClass sc:scs){
				if(sc.getRightArea()!=null && !rightAreaId.equals("")){
					if(sc.getRightArea().getRightAreaId().equals(rightAreaId)){
						selected.append("['"+sc.getSecClassId()+"','"+sc.getClassName()+"'],");
						continue;
					}
				}
				str.append("['"+sc.getSecClassId()+"','"+sc.getClassName()+"'],");
			}
			if(selected.charAt(selected.length()-1)==','){
				selected.deleteCharAt(selected.length()-1);
			}
			if(str.charAt(str.length()-1)==','){
				str.deleteCharAt(str.length()-1);
			}
		}
		selected.append("]");
		str.append("]"+selected);
		return str.toString();
	}
	//返回主页所需对象
	public String gotoIndex(){
		fcList=classifyService.getFirstClassify();
		areaList=moduleService.getAllArea();
		haList=pictureService.getAllHeadAdvert();
		lhaList=new ArrayList<HeadAdvert>();//左边头部广告的list 在JSP中判断location不好使
		rhaList=new ArrayList<HeadAdvert>();//右边头部广告list
		headAps=pictureService.getHeadAdvertPic();
		if(haList.size()>0 && haList!=null){
			for(HeadAdvert ha:haList){
				if(ha.getLocation()==1){
					lhaList.add(ha);
					continue;
				}else if(ha.getLocation()==3){
					rhaList.add(ha);
					continue;
				}
			}
		}
		return SUCCESS;
	}
	//转到商家详细信息页面
	public String getComDel(){
		String companyId=this.getRequest().getParameter("companyId");
		company=classifyService.getCompany(companyId);
		seconds=company.getSecondClass();
		fcList=classifyService.getFirstClassify();
		haList=pictureService.getAllHeadAdvert();
		lhaList=new ArrayList<HeadAdvert>();//左边头部广告的list 在JSP中判断location不好使
		rhaList=new ArrayList<HeadAdvert>();//右边头部广告list
		headAps=pictureService.getHeadAdvertPic();
		if(haList.size()>0 && haList!=null){
			for(HeadAdvert ha:haList){
				if(ha.getLocation()==1){
					lhaList.add(ha);
					continue;
				}else if(ha.getLocation()==3){
					rhaList.add(ha);
					continue;
				}
			}
		}
		return SUCCESS;
	}
	//转到头部广告的页面
	public String getHeadAdvertDetail(){
		String headAdvertId=this.getRequest().getParameter("headAdvertId");
		hal=pictureService.getHeadAdvertListById(headAdvertId);
		headAdvert=hal.getHeadAdvert();
		fcList=classifyService.getFirstClassify();
		haList=pictureService.getAllHeadAdvert();
		lhaList=new ArrayList<HeadAdvert>();//左边头部广告的list 在JSP中判断location不好使
		rhaList=new ArrayList<HeadAdvert>();//右边头部广告list
		headAps=pictureService.getHeadAdvertPic();
		if(haList.size()>0 && haList!=null){
			for(HeadAdvert ha:haList){
				if(ha.getLocation()==1){
					lhaList.add(ha);
					continue;
				}else if(ha.getLocation()==3){
					rhaList.add(ha);
					continue;
				}
			}
		}
		return SUCCESS;
	}
	//将一级分类下的所有二级分类拿出来，然后分两部分，如果是双数个数平分，如果单数则左面多一个，接着判断是否大于4如果大于4就，用4个生成一个marea\rarea,然后放入area
	public String getFirstClassDetail(){
		String firstId=this.getRequest().getParameter("firstId");
		fc=classifyService.getFirstClass(firstId);
		
		Set<SecondClass> scList=fc.getSecondClasses();
		List<MiddleArea> middles=moduleService.getAllMiddle();
		List<RightArea> rights=moduleService.getAllRight();
		
		List<LeftRecommon>lrs=moduleService.getAllLeftRec();
		if(scList.size()>0 && scList!=null){
			if(scList.size()>1){
				int breakPoint;;
				if(scList.size()%2==0){
					breakPoint=scList.size()/2;
				}else{
					breakPoint=scList.size()/2+1;
				}
				int i=1,j=1;
				Set <SecondClass> scs=new HashSet<SecondClass>();//放secondclass 每隔四个就清空一次
				Set<MiddleArea>mas=new HashSet<MiddleArea>();//放所有的中间模块
				Set<RightArea>ras=new HashSet<RightArea>();//放所有的右边模块
				Set<LeftRecommon>left=new HashSet<LeftRecommon>();
				for(SecondClass sc:scList){
					if(i<=breakPoint){//得到分界点前面的也就是中间模块的
						scs.add(sc);
						if(i%4==0 || i==breakPoint){
							Area area=new Area();
							MiddleArea ma=new MiddleArea();
							int ram=(int)Math.random()*middles.size();
							if(middles.size()-1>=((i-1)/4)){
								ma.setAdvertPics(middles.get((i-1)/4).getAdvertPics());
							}else{
								ma.setAdvertPics(middles.get(ram).getAdvertPics());
							}
							ma.setSecondClasses(scs);
							mas.add(ma);
							int lram=(int)Math.random()*lrs.size();
							if(lrs.size()-1>=((i-1)/4)){
								left.add(lrs.get((i-1)/4));//按左边模块的顺序。加入下面的图片
							}else{
								left.add(lrs.get(lram));//随机添加一个左面的模块。加入下面的图片
							}
							
							area.setLeftRecommons(left);
							area.setMiddleAreas(mas);
							scAreaList.add(area);
							scs=new HashSet<SecondClass>();
							mas=new HashSet<MiddleArea>();
							left=new HashSet<LeftRecommon>(); 
						}
					}else{//过了分界点只后的 都是右边模块的,j从1开始计数
						scs.add(sc);
						if(j%4==0 || j==scList.size()-breakPoint){
							Area area=scAreaList.get((j-1)/4);
							RightArea ra=new RightArea();
							ra.setSecondClasses(scs);
							int ram=(int)Math.random()*middles.size();
							if(rights.size()-1>=((j-1)/4)){
								ra.setAdvertPics(rights.get((j-1)/4).getAdvertPics());
							}else{
								ra.setAdvertPics(rights.get(ram).getAdvertPics());
							}
							ras.add(ra);
							area.setRightAreas(ras);
							//scAreaList.add(area);
							scs=new HashSet<SecondClass>();
							ras=new HashSet<RightArea>();
						}
						j++;
					}
					i++;
				}
			}
		}
		fcList=classifyService.getFirstClassify();
		haList=pictureService.getAllHeadAdvert();
		lhaList=new ArrayList<HeadAdvert>();//左边头部广告的list 在JSP中判断location不好使
		rhaList=new ArrayList<HeadAdvert>();//右边头部广告list
		headAps=pictureService.getHeadAdvertPic();
		if(haList.size()>0 && haList!=null){
			for(HeadAdvert ha:haList){
				if(ha.getLocation()==1){
					lhaList.add(ha);
					continue;
				}else if(ha.getLocation()==3){
					rhaList.add(ha);
					continue;
				}
			}
		}
		return SUCCESS;
	}
	
	//将一级分类下的所有二级分类拿出来，然后分两部分，如果是双数个数平分，如果单数则左面多一个，接着判断是否大于4如果大于4就，用4个生成一个marea\rarea,然后放入area
	public String getSecondClassDetail(){
		String secondId=this.getRequest().getParameter("secondId");
		SecondClass sc=classifyService.getSecondClass(secondId);
		
		Set<Company> comList=sc.getCompanies();
		List<MiddleArea> middles=moduleService.getAllMiddle();
		//List<RightArea> rights=moduleService.getAllRight();
		//Set<SecondClass> scList=fc.getSecondClasses();
		List<LeftRecommon>lrs=moduleService.getAllLeftRec();
		if(comList.size()>0 && comList!=null){
			if(comList.size()>=1){
				int breakPoint;;
				/*if(comList.size()%2==0){
					breakPoint=comList.size()/2;
				}else{
					breakPoint=comList.size()/2+1;
				}*/
				breakPoint=comList.size();
				int i=1;//j=1;
				Set<Company> leftComs=new HashSet<Company>();
//				Set<Company> rightComs=new HashSet<Company>();
				Set <SecondClass> scs=new HashSet<SecondClass>();//放secondclass 每隔四个就清空一次
				Set<MiddleArea>mas=new HashSet<MiddleArea>();//放所有的中间模块
				Set<RightArea>ras=new HashSet<RightArea>();//放所有的右边模块
				Set<LeftRecommon>left=new HashSet<LeftRecommon>();
				for(Company com:comList){
					if(i<=breakPoint){//得到分界点前面的也就是中间模块的
						leftComs.add(com);
						if(i%20==0 || i==breakPoint){
							/*Area area=new Area();
							MiddleArea ma=new MiddleArea();
							SecondClass second=new SecondClass();
							second.setCompanies(leftComs);
							scs.add(second);
							ma.setSecondClasses(scs);;
							ma.setAdvertPics(middles.get((i-1)/20).getAdvertPics());
							mas.add(ma);
							area.setMiddleAreas(mas);
							
							left.add(lrs.get((i-1)/20));//随机左列推荐
							area.setLeftRecommons(left);
							
							scAreaList.add(area);
							leftComs=new HashSet<Company>();//清空
							scs=new HashSet<SecondClass>();
							mas=new HashSet<MiddleArea>();
							left=new HashSet<LeftRecommon>();*/ 
						}
					}else{//过了分界点只后的 都是右边模块的,j从1开始计数
						/*rightComs.add(com);
						if(j%20==0 || j==comList.size()-breakPoint){
							System.out.println(j+":"+scAreaList.size());
							Area area=scAreaList.get((j-1)/20);
							RightArea ra=new RightArea();
							SecondClass second=new SecondClass();
							second.setCompanies(rightComs);
							scs.add(second);
							ra.setSecondClasses(scs);
							ra.setAdvertPics(rights.get((i-1)/20).getAdvertPics());
							ras.add(ra);
							area.setRightAreas(ras);
							//scAreaList.add(area);
							rightComs=new HashSet<Company>();
							scs=new HashSet<SecondClass>();
							ras=new HashSet<RightArea>();
						}
						j++;*/
					}
					i++;
				}
				Area area=new Area();
				MiddleArea ma=new MiddleArea();
				SecondClass second=new SecondClass();
				second.setCompanies(comList);
				scs.add(second);
				ma.setSecondClasses(scs);;
				int ram=(int)Math.random()*middles.size();
				ma.setAdvertPics(middles.get(ram).getAdvertPics());
				mas.add(ma);
				area.setMiddleAreas(mas);
				
				int lram=(int) (Math.random()*lrs.size());
				left.add(lrs.get(lram));//随机左列推荐
				area.setLeftRecommons(left);
				
				aplist=pictureService.getSecondPicList();
				if(aplist!=null && aplist.size()>0){
					RightArea ra=new RightArea();//右侧图片
					ras.add(ra);
					area.setRightAreas(ras);
				}
				scAreaList.add(area);
			}
		}
		fcList=classifyService.getFirstClassify();
		haList=pictureService.getAllHeadAdvert();
		lhaList=new ArrayList<HeadAdvert>();//左边头部广告的list 在JSP中判断location不好使
		rhaList=new ArrayList<HeadAdvert>();//右边头部广告list
		headAps=pictureService.getHeadAdvertPic();
		if(haList.size()>0 && haList!=null){
			for(HeadAdvert ha:haList){
				if(ha.getLocation()==1){
					lhaList.add(ha);
					continue;
				}else if(ha.getLocation()==3){
					rhaList.add(ha);
					continue;
				}
			}
		}
		return SUCCESS;
	}
	
	//给公司换掉主图片
	@SuppressWarnings("deprecation")
	public String uploadCompanyMainPic(){
		String companyId=this.getRequest().getParameter("companyId");
		Company c=classifyService.getCompany(companyId);
		MultiPartRequestWrapper wrapper=(MultiPartRequestWrapper) this.getRequest();
		File[] file=wrapper.getFiles("fileName");
		BufferedInputStream in = null ;
		BufferedOutputStream out = null ;
		Date date=new Date();
		try {
			for(int i=0;i<file.length;i++){
				 in = new BufferedInputStream( new FileInputStream(file[i]), BUFFER_SIZE);
				 out = new BufferedOutputStream( new FileOutputStream(new File(this.getRequest().getRealPath("/upload")+"/"+c.getCompanyId()+date.getTime()+".jpg")), BUFFER_SIZE);
                 byte [] buffer = new byte [BUFFER_SIZE];
                 while (in.read(buffer) > 0 ) {
                    out.write(buffer);
                 }
                 c.setMainPic("/upload/"+c.getCompanyId()+date.getTime()+".jpg");
                 out.flush();
			}
			classifyService.createCompany(c);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	//返回商家的所有图片，第一张为主图片显示在上方
	public void loadCompanyPicList(){
		String companyId=this.getRequest().getParameter("companyId");
		Company company=classifyService.getCompany(companyId);
		Set<AdvertPic> comPics=company.getAdvertPics();
		StringBuffer str=new StringBuffer("{success:true,root:[");
		if(comPics!=null && comPics.size()>0){
			for(AdvertPic ap:comPics){
				str.append("{picName:'"+ap.getPicName()+"',picUrl:'"+ap.getPicUrl()+"',picId:'"+ap.getAdvertPicId()+"',displayOrder:'"+ap.getDisplayOrder()+"'},");
			}
			str.deleteCharAt(str.length()-1);
		}
		str.append("]}");
		this.sendMessage(str.toString());
	}
	
	//给商家上传广告图片
	@SuppressWarnings("deprecation")
	public String uploadCompanyPic(){
		String companyId=this.getRequest().getParameter("companyId");
		Company company=classifyService.getCompany(companyId);
		String picName=this.getRequest().getParameter("picName");
		MultiPartRequestWrapper wrapper=(MultiPartRequestWrapper) this.getRequest();
		File[] file=wrapper.getFiles("fileName");
		System.out.println(wrapper.getContentType()+"---------");
		BufferedInputStream in = null ;
		BufferedOutputStream out = null ;
		Date date=new Date();
		AdvertPic ap=new AdvertPic();
		ap.setCompany(company);
		Set<AdvertPic>aps=company.getAdvertPics();
		try {
			for(int i=0;i<file.length;i++){
				 in = new BufferedInputStream( new FileInputStream(file[i]), BUFFER_SIZE);
				 out = new BufferedOutputStream( new FileOutputStream(new File(this.getRequest().getRealPath("/upload")+"/"+company.getCompanyId()+date.getTime()+".jpg")), BUFFER_SIZE);
                 byte [] buffer = new byte [BUFFER_SIZE];
                 while (in.read(buffer) > 0 ) {
                    out.write(buffer);
                 }
                 ap.setPicUrl("/upload/"+company.getCompanyId()+date.getTime()+".jpg");
                 ap.setPicName(picName);
                 String displayOrder=this.getRequest().getParameter("displayOrder");
                 if(displayOrder.equals("")){
                	 displayOrder="1";
                 }
                 ap.setDisplayOrder(Integer.valueOf(displayOrder));
                 aps.add(ap);
                 company.setAdvertPics(aps);
                 out.flush();
			}
			classifyService.createCompany(company);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	public void getAllFirstClassArray(){
		List <FirstClass> fcs=classifyService.getFirstClassify();
		StringBuffer str=new StringBuffer("[");
		if(fcs.size()>0 && fcs!=null){
			for(FirstClass fc:fcs){
				str.append("['"+fc.getFirstClassId()+"','"+fc.getClassName()+"'],");
			}
			str.deleteCharAt(str.length()-1);
		}
		str.append("]");
		this.sendMessage(str.toString());
	}
	
	public void getAllSecondClassArray(){
		String firstClassId=this.getRequest().getParameter("firstClassId");
		FirstClass fc=classifyService.getFirstClass(firstClassId);
		Set<SecondClass> scs=fc.getSecondClasses();
		StringBuffer str=new StringBuffer("[");
		if(scs.size()>0 && scs!=null){
			for(SecondClass sc:scs){
				str.append("['"+sc.getSecClassId()+"','"+sc.getClassName()+"'],");
			}
			str.deleteCharAt(str.length()-1);
		}
		str.append("]");
		this.sendMessage(str.toString());
	}
	public void getAllCompanyArray(){
		String secondClassId=this.getRequest().getParameter("secondClassId");
		SecondClass sc=classifyService.getSecondClass(secondClassId);
		Set<Company> cs=sc.getCompanies();
		StringBuffer str=new StringBuffer("[");
		if(cs.size()>0 && cs!=null){
			for(Company c:cs){
				str.append("['"+c.getCompanyId()+"','"+c.getCompanyName()+"'],");
			}
			str.deleteCharAt(str.length()-1);
		}
		str.append("]");
		this.sendMessage(str.toString());
	}
	//保存一条评论
	public void saveCommentDetail(){
		String companyId=this.getRequest().getParameter("companyId");
		Company company=classifyService.getCompany(companyId);
		Comment comment;
		String commentDet=this.getRequest().getParameter("commentDet");
		String commentGrade=this.getRequest().getParameter("commentGrade");
		String commentator=this.getRequest().getParameter("commentator");
		String stronger=this.getRequest().getParameter("stronger");
		System.out.println(commentDet+":"+commentGrade+":"+commentator+":"+stronger);
		CommentDetail cd=new CommentDetail();
		cd.setCommentator(commentator);
		if(!commentator.equals("")){
			cd.setCommentator(commentator);
		}else{
			if(stronger!=null && stronger.equals("1")){
				cd.setCommentator("匿名发表");
			}
		}
		cd.setCommentDet(commentDet);
		cd.setCommentGrade(commentGrade);
		Date date=new Date();
		cd.setCommentDate(new Timestamp(date.getTime()));
		if(company.getComments().size()>0 && company.getComments()!=null){
			comment=(Comment) company.getComments().toArray()[0];
		}else{
			comment=new Comment();
		}
		cd.setComment(comment);
		Set<CommentDetail> cds=new HashSet <CommentDetail> ();
		cds.add(cd);
		comment.setCommentDetails(cds);
		Set<Comment>comments=new HashSet<Comment>();
		comment.setCompany(company);
		comments.add(comment);
		company.setComments(comments);
		classifyService.createCompany(company);
	}
	//取出商家的评论
	public void getAllCommentDetail(){
		String companyId=this.getRequest().getParameter("companyId");
		int start=Integer.valueOf(this.getRequest().getParameter("start"));
		int limit=Integer.valueOf(this.getRequest().getParameter("limit"));
		Company company=classifyService.getCompany(companyId);
		
		StringBuffer str=new StringBuffer("{results:");
		Comment comment=null;
		
		if(company.getComments()!=null && company.getComments().size()>0){
			comment=(Comment) company.getComments().toArray()[0];
			str.append(comment.getCommentDetails().size()+",root:[");
		}else{
			this.sendMessage("{root:[],results:0}");
			return;
		}
		List<CommentDetail> cds=new ArrayList<CommentDetail>();
		cds=classifyService.getAllCommentDetail(comment.getCommentId(), start, limit);
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(cds!=null && cds.size()>0){
			for(CommentDetail cd:cds){
				String date=sdf.format(cd.getCommentDate());
				str.append("{commentDetailId:'"+cd.getCommentDetailId()+"',commentDet:'"+cd.getCommentDet()+"',commentGrade:'"+cd.getCommentGrade()+"',commentator:'"+cd.getCommentator()+"',commentDate:'"+date+"'},");
			}
			str.deleteCharAt(str.length()-1);
		}
		str.append("]}");
		this.sendMessage(str.toString());
	}
	//搜索
	public String getSearchDetl() throws UnsupportedEncodingException{
		String searchValue=this.getRequest().getParameter("searchValue");
		searchValue=java.net.URLDecoder.decode(searchValue,"UTF-8");
		List <Company> coms=classifyService.getSearchDetl(searchValue);
		Set <Company> comSet=new HashSet<Company>();
		for(Company com:coms){
			comSet.add(com);
		}
		
		List<MiddleArea> middles=moduleService.getAllMiddle();
		List<LeftRecommon>lrs=moduleService.getAllLeftRec();
		if(comSet.size()>0 && comSet!=null){
			if(comSet.size()>=1){
				Set <SecondClass> scs=new HashSet<SecondClass>();//放secondclass 每隔四个就清空一次
				Set<MiddleArea>mas=new HashSet<MiddleArea>();//放所有的中间模块
				Set<RightArea>ras=new HashSet<RightArea>();//放所有的右边模块
				Set<LeftRecommon>left=new HashSet<LeftRecommon>();
				
				Area area=new Area();
				MiddleArea ma=new MiddleArea();
				SecondClass second=new SecondClass();
				second.setCompanies(comSet);
				scs.add(second);
				ma.setSecondClasses(scs);;
				int ram=(int)Math.random()*middles.size();
				ma.setAdvertPics(middles.get(ram).getAdvertPics());
				mas.add(ma);
				area.setMiddleAreas(mas);
				
				int lram=(int) (Math.random()*lrs.size());
				left.add(lrs.get(lram));//随机左列推荐
				area.setLeftRecommons(left);
				
				aplist=pictureService.getSecondPicList();
				if(aplist!=null && aplist.size()>0){
					RightArea ra=new RightArea();//右侧图片
					ras.add(ra);
					area.setRightAreas(ras);
				}
				scAreaList.add(area);
			}
		}
		
		
		fcList=classifyService.getFirstClassify();
		haList=pictureService.getAllHeadAdvert();
		lhaList=new ArrayList<HeadAdvert>();//左边头部广告的list 在JSP中判断location不好使
		rhaList=new ArrayList<HeadAdvert>();//右边头部广告list
		headAps=pictureService.getHeadAdvertPic();
		if(haList.size()>0 && haList!=null){
			for(HeadAdvert ha:haList){
				if(ha.getLocation()==1){
					lhaList.add(ha);
					continue;
				}else if(ha.getLocation()==3){
					rhaList.add(ha);
					continue;
				}
			}
		}
		return SUCCESS;
	}
	public List<HeadAdvert> getHaList() {
		return haList;
	}
	public void setHaList(List<HeadAdvert> haList) {
		this.haList = haList;
	}
	public PictureService getPictureService() {
		return pictureService;
	}
	public void setPictureService(PictureService pictureService) {
		this.pictureService = pictureService;
	}
	public List<HeadAdvert> getLhaList() {
		return lhaList;
	}
	public void setLhaList(List<HeadAdvert> lhaList) {
		this.lhaList = lhaList;
	}
	public List<HeadAdvert> getRhaList() {
		return rhaList;
	}
	public void setRhaList(List<HeadAdvert> rhaList) {
		this.rhaList = rhaList;
	}
	public List<AdvertPic> getHeadAps() {
		return headAps;
	}
	public void setHeadAp(List<AdvertPic> headAps) {
		this.headAps = headAps;
	}
	public SecondClass getSeconds() {
		return seconds;
	}
	public void setSeconds(SecondClass seconds) {
		this.seconds = seconds;
	}
	public List<Area> getScAreaList() {
		return scAreaList;
	}
	public void setScAreaList(List<Area> scAreaList) {
		this.scAreaList = scAreaList;
	}
	public HeadAdvert getHeadAdvert() {
		return headAdvert;
	}
	public void setHeadAdvert(HeadAdvert headAdvert) {
		this.headAdvert = headAdvert;
	}
	public List<AdvertPic> getAplist() {
		return aplist;
	}
	public void setAplist(List<AdvertPic> aplist) {
		this.aplist = aplist;
	}

}
